﻿define(function (require, exports, module) {
    var selfModuleName = 'question';
    var moduleCommon = require('common');
    var btnNextQuestion = $('#btnNextQuestion');
    var switchTimer, getAnswerTimer, calculateTimeTimer;
    var questionId = 0;
    var nextQuestionId = 0;
    var useTimeCount = 0;
    var isBegin = false;
    var isOver = false;
    var currentBatchIndex = 0;
    var currentQuestionIndex = 0;
    var questionBatch;
    var questoinBatchId;
    var overQuestionBtn = $('#question #overQuestion');

    exports.init = function () {
        // $('body').on('active', function () {
            overQuestionBtn.hide();
            $('#question #beginAnswer').on('click', function () {
                getQuestionBatch();
            });

            $('#question #btnShowAnswer').on('click', function () {
                if (!$('#question #questionContent ul li[data-iscorrect="1"]').hasClass('on')) {
                    $.extendGetJSON(Show_QuestionAnswer, {'questionId': questionId}, function () {
                    }, function () {
                    });
                    var _text = $('#question #questionContent ul li[data-iscorrect="1"] label').text();
                    $('#question #questionContent ul li[data-iscorrect="1"] label').remove();
                    $('#question #questionContent ul li[data-iscorrect="1"]').addClass('on').append('<label><i class="iconfont">&#xe619;</i>' + _text + '</label>');
                    getQuestionAnswerRank();
                    isOver = true;
                }
            });
            overQuestionBtn.on('click', function () {
                getQuestionAnswerRank(true);
                isOver = true;
            });
        // });

        // $('body').on('modulechange', function (e, moduleName) {
        //     if (moduleName == selfModuleName) {
                $('#question').show();
                if (isBegin) {
                    //calculateTime();
                } else {
                    stepSwitch();
                }
            // }
            // else {
            //     $('#question').hide();
            //     if (isBegin)
            //         clearInterval(calculateTimeTimer);
            //     else
            //         clearInterval(switchTimer);
            // }
        // });
    };

    //步骤切换显示
    var stepSwitch = function () {
        switchTimer = setInterval(function () {
            $('.description').each(function (index, element) {
                if ($(this).css('opacity') == 1) {
                    $(this).animate({'opacity': 0}, function () {
                        $(this).siblings('.description').animate({'opacity': 1});
                    });
                }
            });
        }, 5000);
    };

    var getQuestionBatch = function () {

        $.extendGetJSON(Get_QuestionForTemp, {}, function (data) {
            console.log(2);
            if (data.ResultType==1) {
                questionBatch = data.Question;
                questoinBatchId = questionBatch[currentBatchIndex].id;
                questionId = questionBatch[currentBatchIndex].Question[currentQuestionIndex].QuestionID;

                getQuestion(true, questionId);
            } else {
                moduleCommon.showInfo('已经没有题目了，请从后台添加!');
            }
        }, function () {
        });
    };
    var calculateTime = function () {
        isBegin = false;
        calculateTimeTimer = setInterval(function () {
            $('#question #Question_UseTime i').html(useTimeCount++);
        }, 1000);
    };

    //获取问题
    var getQuestion = function (isFirst, id) {
        getQuestionAnswerRank();

        moduleCommon.loading('数据正在准备中，请稍后');
        $.extendGetJSON(Get_Question, {
            'isFirst': isFirst ? 'True' : 'False',
            'questionID': id
        }, function (data) {
            moduleCommon.loaded();
            btnNextQuestion.html('下一题');
            isOver = false;
            if (data.ResultType != 1) {
                moduleCommon.showInfo(data.Message);
                return;
            } else {
                questionId = id;
                useTimeCount = 0;
                clearInterval(calculateTimeTimer);
                calculateTime();
                if (isFirst) {
                    clearInterval(switchTimer);
                    isBegin = true;
                    $('#question .question-index').remove();
                    $('#question #showQuestion').show();
                    getQuestionAnswerRecords();
                }

                var question = data.AppendData;
                $('#question #Question_Number i').html(question.UsedCount);

                $('#question #questionContent ul').empty();
                var strLi = '';
                var options = question.Options;
                var charArray = ['A', 'B', 'C', 'D'];
                for (var i = 0; i < options.length; i++) {
                    strLi += '<li data-optionid="' + options[i].Id + '" data-iscorrect="' + options[i].IsCorrect + '"><span class="question-title">' + charArray[i] + '：' + options[i].Content + '</span></li>';
                }
                $('#question #questionContent ul').html(strLi);
                $('#question #questionContent h2').html(question.Content);
                currentQuestionIndex++;
                if (currentQuestionIndex >= questionBatch[currentBatchIndex].Question.length) {
                    currentBatchIndex++;

                    if (currentBatchIndex >= questionBatch.length) {
                        btnNextQuestion.hide();
                    } else {
                        overQuestionBtn.show();
                        btnNextQuestion.hide().html('下一轮').attr('data-nextbatch', 1);
                        currentQuestionIndex = 0;
                        nextQuestionId = questionBatch[currentBatchIndex].Question[currentQuestionIndex].QuestionID;
                    }
                } else {
                    btnNextQuestion.html('下一题');
                    nextQuestionId = questionBatch[currentBatchIndex].Question[currentQuestionIndex].QuestionID;
                }
                btnNextQuestion.on('click', function () {
                    btnNextQuestion.off('click');
                    if (btnNextQuestion.attr('data-nextbatch') == 1) {
                        questoinBatchId = questionBatch[currentBatchIndex].Bid;
                        $('#question #showList table tr:gt(0)').remove();
                        btnNextQuestion.attr('data-nextbatch', 0);
                    }
                    getQuestion(false, nextQuestionId);
                });
            }
        }, function () {
            moduleCommon.loaded();
            moduleCommon.showInfo('网络繁忙，请稍后重试');
        });
    };

    //获取粉丝答题记录
    var getQuestionAnswerRecords = function () {
        getAnswerTimer = setInterval(function () {
            if (questionId <= 0)
                return;
            $.extendGetJSON(Get_QuestionAnswerRecords, {'questionId': questionId}, function (data) {
                if (data && data.length > 0 && isOver == false) {
                    var submitAnswerFansCount = 0;
                    $.each(data, function (iOption, option) {
                        $('#question #questionContent ul li[data-optionid="' + option.OptionId + '"] div').remove();
                        var strDiv = '<div>';
                        var answers = option.Answers;
                        submitAnswerFansCount += answers.length;
                        for (var i = 0; i < (answers.length > 4 ? 4 : answers.length); i++)
                            strDiv += '<img onerror="imgError(this);"  src="' + answers[i].Head + '" />';
                        if ($('#question #questionContent ul li[data-optionid="' + option.OptionId + '"]').hasClass('on')) {
                            strDiv += '</div><label><i class="iconfont">&#xe619;</i>' + (answers.length > 3 ? '等' : '') + answers.length + '名答对</label>';
                            $('#question #questionContent ul li[data-optionid="' + option.OptionId + '"] label').remove();
                        }
                        else
                            strDiv += '<label>' + (answers.length > 4 ? '等' : '') + answers.length + '人选择</label></div>';
                        $('#question #questionContent ul li[data-optionid="' + option.OptionId + '"]').append(strDiv);
                    });
                    $('#question #Question_LeftUser i').html(submitAnswerFansCount);
                }
            });

        }, 2000);
    };

    var getQuestionAnswerRank = function (type) {
        if (type) {
            var screenId = $('#GetQuestionAnswerRank').val().split('/')[1];
            $.extendGetJSON('http://activity.kxdpm.com/Home/RemoveCache?key=kxdScreenQuestion_' + screenId, {}, function (data) {
            });
            $.extendGetJSON('http://activity.kxdpm.com/Home/RemoveCache?key=kxdScreenQuestionOptions_' + screenId, {}, function (data) {
            });
        }
        $.extendGetJSON(Get_QuestionAnswerRank, {
            'count': 10,
            'batchId': questoinBatchId
        }, function (data) {
            if (data && data.length > 0) {
                $('#question #showList table tr:gt(0)').remove();
                $.each(data, function (i, ele) {
                    $('#question #showList table').append('<tr><td><div><span>' + (i + 1) + '</span>' + ele.Fans_NickName + '</div></td><td>' + ele.Count + '</td><td>' + ele.Second + '</td></tr>');
                });
            }
            if (type) {
                overQuestionBtn.hide();
                if (btnNextQuestion.html() == '下一轮') {
                    btnNextQuestion.show();
                }
            }
        });
    };
});